using System;
using System.Collections.Generic;
using System.Reflection;
using Mistral.Utils;

namespace Mistral.SecureDrive
{
	public class PluginManager
	{
		readonly Dictionary<string,IPlugin> _plugins = new Dictionary<string, IPlugin>( );
		
		public void Run( Assembly assembly, string[] args )
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies( );
			foreach ( Assembly domainAssembly in assemblies )
			{
				Type[] types = ReflectionUtils.GetTypesFromAssembly( domainAssembly, new Predicate<Type>( HasPluginAttribute ) );
				foreach ( Type pluginType in types )
				{
					PluginAttribute pluginAttribute = GetPluginAttribute( pluginType );
					_plugins.Add( pluginAttribute.Name, (IPlugin)Activator.CreateInstance( pluginType ) );	
				}				
			}
		}

		private static bool HasPluginAttribute( Type type )
		{
			return GetPluginAttribute( type ) != null;
		}
		
		private static PluginAttribute GetPluginAttribute( Type type )
		{
			object[] attributes = type.GetCustomAttributes( typeof( PluginAttribute ), true );
			return attributes != null && attributes.Length > 0 ? (PluginAttribute)attributes[0] : null;
		}

		public IPlugin GetPlugin( string pluginName )
		{
			return _plugins[pluginName];
		}
	}
}